<?php

/**
 * 广告信息表
 */
use Common\Bridge;
use lib\core\AdminAction;
use Center\Ads as AD;

define('SITE_AUTH', 'ads-list');
require('../../../common.inc.php');

class ads extends AdminAction
{
    private $pdo_r;

//    private $field = [
//        'Id' => '店铺id',
//        'CityId' => '所属城市id',
//        'CateId' => '分类id',
//        'Name' => '店铺名称',
//        'Description' => '店铺描述',
//        'Keywords' => '搜索用关键字',
//        'Cover' => '店铺广告封面图',
//        'UserId' => '管理用户ID',
//        'Address' => '店铺地址',
//        'Mobile' => '店铺电话',
//        'Content' => '店铺内容',
//        'Status' => [0 => '普通商家', 1 => '付费商家', 2 => '过期商家'],
//        'UpdateTime' => '更新时间',
//        'CreateTime' => '创建时间',
//        'Members' => '会员数'
//    ];

    private $primary_key = 'Id';
    private $list_url = '/data/modules/ads/ads.php';

    public function doDefault()
    {
        $param['ShopId'] = (int)$_GET['ShopId'];
        $param['AdType'] = (int)$_GET['AdType'];
        $param['Status'] = (int)$_GET['Status'];
        $param['Title'] = trim($_GET['Title']);

        $page = empty($_GET['page']) ? 1 : (int)$_GET['page'];
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $where = "1";
        if ($param['ShopId'] > 0) {
            $where .= " AND ShopId = " . $param['ShopId'];
        }
        if ($param['Status'] > 0) {
            $where .= " AND Status = " . $param['Status'];
        }
        if ($param['Title'] != '') {
            $where .= " AND Title LIKE '%" . $param['Title'] . "%'";
        }

        $primary_key = $this->primary_key;
        $count_sql = "SELECT COUNT($primary_key) AS `num` FROM `Ads` WHERE $where";

        $count = $this->readDb($count_sql);
        $count = (int)$count[0]['num'];

        $sql = "SELECT * FROM `Ads` WHERE $where order by `Sort` ASC LIMIT $offset,$limit";
        $data = $this->readDb($sql);

        $smarty = $this->app->page();
        if ($count > 0) {
            if (!empty($data)) {
                $smarty->value('list', $data);
            }

            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;
            $smarty->value('page_info', $page_info);

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('pagination', $pagination);
        }

        $smarty->value('status', [1 => '正常', 2 => '失效']);
        $smarty->value('adtype', [1 => '竞价', 2 => '按次']);
        $smarty->value('param', $param);
        $smarty->output('ads/ads.tpl');
    }

    /**
     *
     */
    public function doEdit()
    {
        $id = (int)$_GET['Id'];
        if ($id < 1) {
            HDshowMsg('操作失败！', ['type' => 'error', 'desc' => 'Id为空']);
        }

        $sql = "SELECT * FROM Ads WHERE Id = $id";
        $list = $this->readDb($sql);

        $smarty = $this->app->page();
        $data = current($list);
        $smarty->value('status', [1 => '正常', 2 => '失效']);
        $smarty->value('adtype', [1 => '竞价', 2 => '按次']);
        $smarty->value('info', $data);
        $smarty->output('ads/adsedit.tpl');
    }

    public function doAdd()
    {
        $smarty = $this->app->page();
//        $smarty->value('info', current($list));
        $smarty->output('ads/adsadd.tpl');
    }

    public function doUpdate()
    {
        $id = intval($_POST['Id']);
        if (empty($id) || empty($_POST['Title'])) {
            HDshowMsg('修改失败1！', ['type' => 'error', 'url' => $this->list_url]);
        }

        //上传图片
        $img = $_FILES['Cover'];
        if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0) {
            // 复制图片
            $imgUrlAddre = self::saveImageUrl($id, $_FILES['Cover']);
        } else {
            $imgUrlAddre = false;
        }

        $data = [
            'CityId' => intval($_POST['CityId']),
            'ShopId' => intval($_POST['ShopId']),
            'Title' => trim($_POST['Title']),
            'Description' => trim($_POST['Description']),
            'Content' => trim($_POST['Content']),
            'StartTime' =>  trim($_POST['StartTime']),
            'EndTime' => trim($_POST['EndTime']),
            'Order' => intval($_POST['Order']),
            'AdFee' => intval($_POST['AdFee']),
            'AdType' => intval($_POST['AdType']),
            'LinkUrl' => trim($_POST['LinkUrl']),
            'MaxCount' => intval($_POST['MaxCount']),
            'Status' => intval($_POST['Status']),
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];
        if ($imgUrlAddre !== false) {
            $data['Cover'] = $imgUrlAddre;
        }
        $rel = AD::update($id, $data);
        if ($rel) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    public function doInput()
    {
        if (empty($_POST['Title'])) {
            HDshowMsg('修改失败1！', ['type' => 'error', 'url' => $this->list_url]);
        }

        $data = [
            'CityId' => intval($_POST['CityId']),
            'ShopId' => intval($_POST['ShopId']),
            'Title' => trim($_POST['Title']),
            'Description' => trim($_POST['Description']),
            'Content' => trim($_POST['Content']),
            'StartTime' =>  trim($_POST['StartTime']),
            'EndTime' => trim($_POST['EndTime']),
            'Order' => intval($_POST['Order']),
            'AdFee' => intval($_POST['AdFee']),
            'AdType' => intval($_POST['AdType']),
            'LinkUrl' => trim($_POST['LinkUrl']),
            'MaxCount' => intval($_POST['MaxCount']),
            'Status' => intval($_POST['Status']),
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];
        $id = Ad::add($data);
        if ($id !== false && $id > 0) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
        //上传图片
        $img = $_FILES['Cover'];
        if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0 && $id) {
            // 复制图片
            $imgUrlAddre = self::saveImageUrl($id, $_FILES['Cover']);
            AD::update($id, ['Cover' => $imgUrlAddre]);
        }

        if ($id) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    /**
     * 利用SQL语句读取数据库并返回相应数据
     *
     * @param $sql
     * @return mixed
     */
    private function readDb($sql)
    {
        $pdo = $this->pdo_r;
        if (empty($pdo)) {
            $pdo = $this->pdo_r = Bridge::pdo(Bridge::DB_CENTER_W);
        }

        $obj = $pdo->query($sql);

        return $obj->fetchAll();
    }

    /**
     * @param $filename
     * @return bool|string
     */
    private static function saveImageUrl($id, $filename)
    {
        ///
        $upload_dir = \Common\ResourcePathManager::getADSImgSavePath();

        $hash = \Common\PhotoImage::getImageHash($id);
        //$src_img = $upload_dir . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg";
        $image_status = \Common\PhotoImage::checkImage($filename);

        if ($image_status['code'] == 4) {
            $image_status = \Common\PhotoImage::checkImageByUrl($filename);

            if ($image_status['code'] == 4) {
                return false;
            }
        }

        //配置图片上传目录
        $cfg = [
            'base' => $upload_dir,
            'thumb' => [
                'source' => [
                    'url' => '{hash1}/{hash2}/{id}.jpg'
                ],
                '150' => [
                    'width' => 150,
                    'height' => 150,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{hash1}/{hash2}/{id}_150x150.jpg'
                ],
                '300' => [
                    'width' => 300,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{hash1}/{hash2}/{id}_300.jpg'
                ],
                '800' => [
                    'width' => 800,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{hash1}/{hash2}/{id}_800.jpg'
                ]
            ],
            'hash1' => $hash['hash1'],
            'hash2' => $hash['hash2'],
            'id' => $id
        ];

        if ($image_status['status'] == true) {
            $result = \Common\PhotoImage::imageResize($cfg, $image_status);

            if ($result) {
                $res_arr = [
                    "http://img.jinguonet.com/ads/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg",
                    "http://img.jinguonet.com/ads/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_150x150.jpg",
                    "http://img.jinguonet.com/ads/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_300.jpg",
                    "http://img.jinguonet.com/ads/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_800.jpg"
                ];

                return "http://img.jinguonet.com/ads/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg?v=" . time();
            }


        }

        return false;
    }
}

$app->run();